package com.dementors.ui.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.ScrollView;

import com.dementors.R;
import com.dementors.base.BaseFragment;
import com.dementors.base.SpaceItemDecoration;
import com.dementors.data.API;
import com.dementors.model.Martshows;
import com.dementors.model.NewAdsBean;
import com.dementors.model.NewIVBean;
import com.dementors.model.NewIconBean;
import com.dementors.model.NewListBean;
import com.dementors.model.NewMoreListBean;
import com.dementors.net.http.okhttp.callback.OkHttpCallback;
import com.dementors.net.http.okhttp.request.OkHttpRequest;
import com.dementors.ui.activity.ItemActivity;
import com.dementors.ui.adapter.NewListAdapter;
import com.dementors.view.FourImageView;
import com.dementors.view.MyImageView;
import com.dementors.view.MyLinearLayoutManager;
import com.gc.flashview.FlashView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.util.ArrayList;

/**
 * ***********************
 * author:Administrator
 * time:2015/12/3.
 * name:今日特卖上新的fragment
 * step:
 */
public class NewFragment extends BaseFragment {

private com.handmark.pulltorefresh.library.PullToRefreshScrollView ptr_scrollview;
    private int num = 1;//记录RecyclerView的当前页
    private LinearLayoutManager layoutManager;
    private static final int UPDATE_MYIMAGEVIEW = 0;
    private static final int UPDATE_IMAGEVIEW = 1;
    private com.gc.flashview.FlashView fv_today_new;
    private android.support.v7.widget.RecyclerView rv_today_new;
    private ArrayList<Martshows> martshows;//存放recyclerview数据的集合
    private NewListAdapter mAdapter;//recyclerview的适配器
    private ArrayList<String> uris;//FlashView图片集合
    private final ArrayList<Bitmap> bits = new ArrayList<Bitmap>();//存放下载的图片
    private MyImageView btn1, btn2, btn3, btn4, btn5;//上新fragment的flashview下的5个自定义view
    private com.dementors.view.FourImageView fiv;//四张图片展示的自定义控件
    private ArrayList<MyImageView> myivs;//存放MyImageView集合
    int curMyIV = 0;//标记myimageview集合当前位置
    int curIV = 0;//标记imageview集合当前位置
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_MYIMAGEVIEW:
                    myivs.get(curMyIV).setImageView((Bitmap) msg.obj);
                    curMyIV++;
                    if (curMyIV == 5) {
                        curMyIV = 0;
                    }
                    break;
                case UPDATE_IMAGEVIEW:

                    fiv.setImageUrls(bits);
                    break;

            }
        }
    };

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_new;
    }

    @Override
    protected void initViews() {
        fv_today_new = (FlashView) view.findViewById(R.id.fv_today_new);
        rv_today_new = (android.support.v7.widget.RecyclerView) view.findViewById(R.id.rv_today_new);
        fiv = (FourImageView) view.findViewById(R.id.fiv_today_new);
        ptr_scrollview= (PullToRefreshScrollView) view.findViewById(R.id.ptr_scrollview);

    }

    @Override
    protected void initData() {

        initUri();
        initMyivs();
        initRecyclerView();
        getHttpFlashView();
        getHttpButton();
        getHttpImageView();
        getHttpRecyclerView();
        registerLinstener();
    }

    /**
     * 监听器
     */
    private void registerLinstener() {
        ptr_scrollview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ptr_scrollview.onRefreshComplete();
                    }
                },2000);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                getMoreRecyclerView();

            }
        });
        //点击事件监听
        mAdapter.setOnItemClickListener(new NewListAdapter.onItemClickListener() {
            @Override
            public void itemClick(View view, int position) {
                Log.i("oye", "点了没" + martshows.get(position).mid);
                Intent intent=new Intent(getActivity(), ItemActivity.class);
                intent.putExtra("id",martshows.get(position).mid);
                startActivity(intent);
            }
        });
    }

    /**
     * 下拉加载数据（RecyclerView)
     */
    private void getMoreRecyclerView() {
        num++;
        new OkHttpRequest.Builder().url(API.NEW_MORE_LIST_DATA + num + "-30---0-1.html").get(new OkHttpCallback<NewMoreListBean>() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(Response response, NewMoreListBean data) {
                martshows.addAll(data.martshows);
                mAdapter.setList(martshows);
                mAdapter.notifyDataSetChanged();
                ptr_scrollview.onRefreshComplete();
            }


        });

    }

    /**
     * 初始化RecyclerView集合
     */
    private void initRecyclerView() {
        mAdapter = new NewListAdapter(getActivity());
        martshows = new ArrayList<>();
        mAdapter.setList(martshows);
        rv_today_new.setAdapter(mAdapter);
        layoutManager=new MyLinearLayoutManager(getActivity(), MyLinearLayoutManager.VERTICAL, false);
        rv_today_new.setLayoutManager(layoutManager);
        //RecyclerView设置间距
        SpaceItemDecoration myDecoration = new SpaceItemDecoration(20);
        rv_today_new.addItemDecoration(myDecoration);
    }

    /**
     * 初始化MyImageView集合
     */
    private void initMyivs() {
        myivs = new ArrayList<>();
        btn1 = (MyImageView) view.findViewById(R.id.btn1_today_new);
        btn2 = (MyImageView) view.findViewById(R.id.btn2_today_new);
        btn3 = (MyImageView) view.findViewById(R.id.btn3_today_new);
        btn4 = (MyImageView) view.findViewById(R.id.btn4_today_new);
        btn5 = (MyImageView) view.findViewById(R.id.btn5_today_new);
        myivs.add(btn1);
        myivs.add(btn2);
        myivs.add(btn3);
        myivs.add(btn4);
        myivs.add(btn5);
    }


    //初始化uris
    private void initUri() {
        uris = new ArrayList<>();
    }

    //RecyclerView获取数据
    private void getHttpRecyclerView() {
        new OkHttpRequest.Builder().url(API.NEW_MORE_LIST_DATA + num + "-30---0-1.html").get(new OkHttpCallback<NewListBean>() {
            @Override
            public void onError(Request request, Exception e) {
            }

            @Override
            public void onResponse(Response response, NewListBean data) {
                martshows.addAll(data.martshows);
                mAdapter.setList(martshows);
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    //4个imageview获取数据
    private void getHttpImageView() {
        new OkHttpRequest.Builder().url(API.NEW_IMAGEVIEW_SHOW_DATA).get(new OkHttpCallback<NewIVBean>() {
            @Override
            public void onError(Request request, Exception e) {
            }

            @Override
            public void onResponse(Response response, NewIVBean data) {
                final ArrayList<NewIVBean.shortcuts> icons = (ArrayList<NewIVBean.shortcuts>) data.promotion_shortcuts;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            bits.add(Picasso.with(getActivity()).load(icons.get(0).img).get());
                            bits.add(Picasso.with(getActivity()).load(icons.get(1).img).get());
                            bits.add(Picasso.with(getActivity()).load(icons.get(2).img).get());
                            bits.add(Picasso.with(getActivity()).load(icons.get(3).img).get());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        while (true) {
                            if (bits.size() == 4) {
                                handler.sendEmptyMessage(UPDATE_IMAGEVIEW);
                                break;
                            }
                        }
                    }
                }).start();


            }

        });
    }

    //5个button获取数据
    private void getHttpButton() {

        new OkHttpRequest.Builder().url(API.NEW_MYIMAGEVIEW_DATA).get(new OkHttpCallback<NewIconBean>() {
            @Override
            public void onError(Request request, Exception e) {
            }

            @Override
            public void onResponse(Response response, NewIconBean data) {
                final ArrayList<NewIconBean.icon> icons = (ArrayList<NewIconBean.icon>) data.icon_shortcuts;
                for (int i = 0; i < icons.size(); i++) {
                    myivs.get(i).setText(icons.get(i).title);
                    final String string = icons.get(i).img;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Bitmap bit = Picasso.with(getActivity()).load(string).get();
                                Message message = new Message();
                                message.obj = bit;
                                message.what = UPDATE_MYIMAGEVIEW;
                                handler.sendMessage(message);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }

            }


        });
    }

    //获取FlashView图片资源
    private void getHttpFlashView() {
        new OkHttpRequest.Builder().url(API.NEW_FLASHVIEW_DATA).get(new OkHttpCallback<NewAdsBean>() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(Response response, NewAdsBean data) {
                ArrayList<NewAdsBean.Ads> ads = data.ads;
                for (NewAdsBean.Ads ad : ads) {
                    uris.add(ad.img);
                }
                fv_today_new.setImageUris(uris);
            }
        });


    }


}
